const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const { dllDir, publicPath } = require('./path');

// 确定在打包prod时，需要和dll配合的插件
const dllReferPlugins = () => {
  const files = fs.readdirSync(dllDir);
  const jsExp = /.*\.js$/;
  const jsonExp = /.*\.manifest.json$/;
  const plugins = [];
  files.forEach((file) => {
    if (jsExp.test(file)) {
      plugins.push(
        new AddAssetHtmlPlugin({
          filepath: path.resolve(dllDir, file),
          outputPath: 'js',
          publicPath: publicPath[publicPath.length - 1] === '/' ? `${publicPath}js` : `${publicPath}/js`,
        }),
      );
    }
    if (jsonExp.test(file)) {
      plugins.push(
        new webpack.DllReferencePlugin({
          manifest: path.resolve(dllDir, file),
        }),
      );
    }
  });
  return plugins;
};

module.exports = {
  dllReferPlugins,
};
